package datastructure.queue2;

import java.util.Iterator;

/**
 * 环形数组实现队列
 *
 * @author 杨 强
 * @package datastructure.queue2
 * @createTime 2023-03-13 22:52
 */
public class ArrayQueue02<E> implements Queue<E>, Iterable<E>{
    public static void main(String[] args) {
        ArrayQueue02<Integer> queue = new ArrayQueue02<>(5);
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        queue.offer(5);
        queue.offer(6);


        Iterator<Integer> iterator = queue.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        System.out.println("出队了 "  + queue.poll());

        Iterator<Integer> iterator2 = queue.iterator();
        while (iterator2.hasNext()){
            System.out.println(iterator2.next());
        }
    }

    /**
     * 头指针
     */
    private int head = 0;
    /**
     * 尾指针
     */
    private int tail = 0;
    /**
     * 队列的储存数据结构:数据
     */
    private final E[] array;
    /**
     * 队列的容量
     */
    private final int capacity;
    /**
     * 队列元素的个数
     */
    private int size = 0;

    /**
     * 构造方法
     * @param capacity 指定队列的长度
     */
    public ArrayQueue02(int capacity) {
        this.capacity = capacity;
        array = (E[]) new Object[capacity];
    }


    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % capacity;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E value = array[head];
        head = (head + 1) % capacity;
        size--;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;
            int count = 0;

            @Override
            public boolean hasNext() {
                return count < size;
            }

            @Override
            public E next() {
                E value = array[p];
                p = (p + 1) % array.length;
                count++;
                return value;
            }
        };
    }
}
